package com.woniuxy.yoga.progress.service.job;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.yoga.commons.core.model.Result;
import com.woniuxy.yoga.progress.client.OrderClient;
import com.woniuxy.yoga.progress.dao.mapper.MoncardMapper;
import com.woniuxy.yoga.progress.dao.model.Moncard;
import com.woniuxy.yoga.progress.model.exception.ProgressException;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

@Component
public class MoncardExpire {

    @Autowired
    private MoncardMapper moncardMapper;

    @Autowired
    private OrderClient orderClient;


    @XxlJob("moncardExpire")
    @GlobalTransactional(rollbackFor = Exception.class)
    public void moncardExpireJob(){
        System.out.println("月卡到期");
        String jobParam = XxlJobHelper.getJobParam();
        JSONObject jsonObject = JSONObject.parseObject(jobParam);
        Map<String, Object> map = JSONObject.toJavaObject(jsonObject, Map.class);
        //获取订单id
        String orderNum = map.get("orderNum").toString();
        QueryWrapper<Moncard> wrapper = new QueryWrapper<>();
        wrapper.eq("order_num",orderNum);
        Moncard moncard = moncardMapper.selectOne(wrapper);
        //条件筛选
        if (moncard!=null && moncard.getCompleteTime()==null){
            //月卡到期
            moncard.setCompleteTime(DateUtil.format(new Date(System.currentTimeMillis()),"yyyy-MM-dd HH:mm:ss"));
            moncardMapper.updateById(moncard);
            //完成订单
            Result<String> result = orderClient.completeOrder(orderNum);
            if (result.getCode()!=200) throw new ProgressException(result.getCode(),result.getMessage());
        }
    }
}
